package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {

        //1 入参判空
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String phone = dto.getPhone();
        String password = dto.getPassword();
        //2 校验手机号和密码是否存在
        if (StringUtils.isEmpty(phone)&&StringUtils.isEmpty(password)){
            // 游客登录
            HashMap<String, Object> map = new HashMap<>();
            //生成token 返回
            String token = AppJwtUtil.getToken(0L);
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

        //正常登录
        // 检验手机号是否存在
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,phone);
        ApUser user = apUserMapper.selectOne(wrapper);
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //存在 时候比对密码
        String salt = user.getSalt();
        String passwordFromDb = user.getPassword();
        String passwordAfterMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!passwordAfterMd5.equals(passwordFromDb)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码正确 生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        //清空敏感信息
        user.setSalt("");
        user.setPassword("");

        HashMap<String, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);

        //返回数据
        return ResponseResult.okResult(map);

    }
}